%clearvars
close all

filePath = matlab.desktop.editor.getActiveFilename;
fprintf('%s\n',filePath);

repository_base = fileparts(fileparts(filePath));
addpath(fullfile(repository_base, "scripts"));
addpath(fullfile(repository_base, "scripts", "libs"));

session_list{1} = 'sub-A';
session_list{2} = 'sub-B';
session_list{3} = 'sub-C';
session_list{4} = 'sub-D';
session_list{5} = 'sub-E';
session_list{6} = 'sub-F';
session_list{7} = 'sub-G';
session_list{8} = 'sub-H';
session_list{9} = 'sub-I';
session_list{10} = 'sub-J';
session_list{11} = 'sub-K';

%session_idx = 1;
session = session_list{session_idx};

f_base = fullfile(repository_base, 'epochs');
save_base = fullfile(repository_base, 'results');

f_name = fullfile(f_base, strcat(session, '_filt_2_0.1_40.mat'));
mkdir(save_base)

load(f_name)

eeg_ch = 1:64;
eeg_th = [-100 100];

eog_ch = 65:66;
eog_th = [-500 500];

alpha_ttest = 0.01;

ch_idx = 32;

color = ['r' 'g' 'b'];
color_mesh = [0.7 0.7 0.7];

for idx_att = 1:3
    for idx_marker = 1:3
        epochs.att{idx_att}.marker{idx_marker}.rej_th(eeg_ch, eeg_th);
        epochs.att{idx_att}.marker{idx_marker}.rej_th(eog_ch, eog_th);
    end
end

time = epochs.att{1}.marker{1}.time;

for dev = 1:3
    f = figure();
    
    t = [];
    nt = [];
    
    for att = 1:3
        data_plot = mean(epochs.att{att}.marker{dev}.data,3);
        plot(time, data_plot(ch_idx,:), 'color', 'red','color', color(att), 'linewidth', 3)
        hold on
        if dev == att
            t = epochs.att{att}.marker{dev}.data;
        else
            nt = cat(3, nt, epochs.att{att}.marker{dev}.data);
        end
    end
    t = squeeze(t(ch_idx, :, :));
    nt = squeeze(nt(ch_idx, :, :));
    axis ij
    xlabel("Time [s]")
    ylabel("Potential [\muV]")
    set(gca,'FontSize',18)
    xlim([-0.1 0.5])
    xaxis = xlim;
    yaxis = ylim;
    plot([time(1) time(length(time))], [0 0], 'color','k','linestyle','-','linewidth',3)
    plot([0 0], [yaxis(1) yaxis(2)], 'color','k','linestyle','--','linewidth',3)
    
    % ttest    
    [h,p,ci,stats] = ttest2(t,nt,'Dim',2,'Alpha',alpha_ttest);
    plot_ttest(h, time, yaxis, color_mesh);
    
    for att = 1:3
        data_plot = mean(epochs.att{att}.marker{dev}.data,3);
        plot(time, data_plot(ch_idx,:), 'color', 'red','color', color(att), 'linewidth', 3)
    end

    exportgraphics(f, fullfile(save_base, strcat(session, '_responses_to_',num2str(dev),'.png')), 'resolution', 300)
end
